package cn.iocoder.yudao.module.project.service.info;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.module.project.dal.dataobject.constructionunit.ProjectConstructionunitDO;
import cn.iocoder.yudao.module.project.dal.mysql.constructionunit.ProjectConstructionUnitMapper;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.service.impl.DiffParseFunction;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.project.controller.admin.info.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.info.InfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.project.dal.mysql.info.InfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.module.project.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.project.enums.LogRecordConstants.*;

/**
 * 项目信息 Service 实现类
 *
 * @author yanglx
 */
@Service
@Validated
public class InfoServiceImpl implements InfoService {

    @Resource
    private InfoMapper infoMapper;
    @Resource
    protected ProjectConstructionUnitMapper projectConstructionUnitMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    @LogRecord(type = PROJECT_INFO_TYPE, subType = PROJECT_INFO_CREATE_SUB_TYPE, bizNo = "{{#info.id}}",
            success = PROJECT_INFO_CREATE_SUCCESS)
    public Long createInfo(InfoSaveReqVO createReqVO) {
        // 插入
        InfoDO info = BeanUtils.toBean(createReqVO, InfoDO.class);
        infoMapper.insert(info);

        if (CollectionUtil.isNotEmpty(info.getConstructionUnitIds())) {
            projectConstructionUnitMapper.insertBatch(convertList(info.getConstructionUnitIds(),
                    constructionUnitId -> new ProjectConstructionunitDO().setInfoId(info.getId()).setConstructionUnitId(constructionUnitId)));
        }

        // 3. 记录操作日志上下文
        LogRecordContext.putVariable("info", info);
        // 返回
        return info.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = PROJECT_INFO_TYPE, subType = PROJECT_INFO_UPDATE_SUB_TYPE, bizNo = "{{#updateReqVO.id}}",
            success = PROJECT_INFO_UPDATE_SUCCESS)
    public void updateInfo(InfoSaveReqVO updateReqVO) {
        // 校验存在
        InfoDO oldInfo = validateInfoExists(updateReqVO.getId());
        // 更新
        InfoDO updateObj = BeanUtils.toBean(updateReqVO, InfoDO.class);
        infoMapper.updateById(updateObj);

        // 2.2 更新岗位
        updateInfoConstrunctionUnit(updateReqVO, updateObj);

        // 3. 记录操作日志上下文
        LogRecordContext.putVariable(DiffParseFunction.OLD_OBJECT, BeanUtils.toBean(oldInfo, InfoSaveReqVO.class));
        LogRecordContext.putVariable("info", oldInfo);
    }

    private void updateInfoConstrunctionUnit(InfoSaveReqVO reqVO, InfoDO updateObj) {
        Long infoId = reqVO.getId();
        Set<Long> dbConstructionUnitIds = convertSet(projectConstructionUnitMapper.selectListByInfoId(infoId), ProjectConstructionunitDO::getConstructionUnitId);
        // 计算新增和删除的岗位编号
        Set<Long> constructionUnitIds = CollUtil.emptyIfNull(updateObj.getConstructionUnitIds());
        Collection<Long> createConstructionUnitIds = CollUtil.subtract(constructionUnitIds, dbConstructionUnitIds);
        Collection<Long> deleteConstructionUnitIds = CollUtil.subtract(dbConstructionUnitIds, constructionUnitIds);
        // 执行新增和删除。对于已经授权的岗位，不用做任何处理
        if (!CollectionUtil.isEmpty(createConstructionUnitIds)) {
            projectConstructionUnitMapper.insertBatch(convertList(createConstructionUnitIds,
                    constructionUnitId -> new ProjectConstructionunitDO().setInfoId(infoId).setConstructionUnitId(constructionUnitId)));
        }
        if (!CollectionUtil.isEmpty(deleteConstructionUnitIds)) {
            projectConstructionUnitMapper.deleteByInfoIdAndConstructionUnitIdId(infoId, deleteConstructionUnitIds);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = PROJECT_INFO_TYPE, subType = PROJECT_INFO_DELETE_SUB_TYPE, bizNo = "{{#id}}",
            success = PROJECT_INFO_DELETE_SUCCESS)
    public void deleteInfo(Long id) {
        // 校验存在
        InfoDO info = validateInfoExists(id);
        // 删除
        infoMapper.deleteById(id);
        // 2.2 删除用户岗位
        projectConstructionUnitMapper.deleteByInfoId(id);

        // 3. 记录操作日志上下文
        LogRecordContext.putVariable("info", info);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
        public void deleteInfoListByIds(List<Long> ids) {
        // 删除
        infoMapper.deleteByIds(ids);
        // 2. 批量删除用户关联数据
        ids.forEach(id -> {
            projectConstructionUnitMapper.deleteByInfoId(id);
        });
        }


    private InfoDO validateInfoExists(Long id) {
        if (id == null) {
            return null;
        }
        InfoDO info = infoMapper.selectById(id);
        if (info == null) {
            throw exception(INFO_NOT_EXISTS);
        }
        return info;
    }

    @Override
    public InfoDO getInfo(Long id) {
        return infoMapper.selectById(id);
    }

    @Override
    public PageResult<InfoDO> getInfoPage(InfoPageReqVO pageReqVO) {
        return infoMapper.selectPage(pageReqVO);
    }

}